package com.im.service;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;

import org.jivesoftware.smackx.filetransfer.FileTransfer.Status;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import com.core.sdk.core.LogUtil;
import com.im.event.FileType;

public abstract class FileSendProgress implements OutgoingFileTransfer.NegotiationProgress,FileSendProgressListener{
	
	private static final String tag = "FileSendThread";
	
	private File file = null;
	final byte[] buffer = new byte[8192];
	final long fileSize ;
	final String filePath;
	
	final FileType fileType ;
	final String toUserJID;
	String description = null;
	public FileSendProgress(File f,String toUserJID,String description) {
		super();
		this.file = f;
		this.fileSize = f.length();
		this.filePath = f.getAbsolutePath();
		this.toUserJID = toUserJID;
		String fn = this.file.getName().trim().toLowerCase();
		String suffix = fn.substring(fn.lastIndexOf(".")+1);
		
		if (FileTypeUtil.isImage(suffix)) {
			this.fileType = FileType.img;
		} else if (FileTypeUtil.isAudio(suffix)) {
			this.fileType = FileType.audio;
		} else {
			this.fileType = FileType.other;
		}
		this.description = description;
	}

	//文件传输状态发生变化时调用
	@Override
	public void statusUpdated(Status oldStatus, Status newStatus) {
		LogUtil.d(tag, "status.new="+newStatus+" status.old="+oldStatus);
	}
	
	@Override
	public void outputStreamEstablished(OutputStream os) {
		DataInputStream dis = null;
		int total = 0;
		double progress = 0;
		DecimalFormat df = new DecimalFormat("#.##");
		try {
			dis = new DataInputStream(new FileInputStream(file));
			int r = -1 ;
			while( (r=dis.read(buffer, 0, buffer.length)) != -1){
				os.write(buffer, 0, r);
				total+=r;
				progress = total * 100d / fileSize;
				os.flush();
				onSendProgress(df.format(progress));
			}
			os.close();
			os = null;
			dis.close();
			dis = null;
			onSendSuccess();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally{
			if(os != null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				os = null;
			}
			if(dis != null){
				try {
					dis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				dis = null;
			}
		}
	}
	
	//当在谈判进程中出现异常时调用
	@Override
	public void errorEstablishingStream(Exception e) {
		onSendException(e);
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public long getFileSize() {
		return fileSize;
	}

	public FileType getFileType() {
		return fileType;
	}

	public String getFilePath() {
		return filePath;
	}

	public String getToUserJID() {
		return toUserJID;
	}

	public String getDescription() {
		return description;
	}
	
	
	
	
}
